/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 *
 * @author thaidacvinh
 */
public class UserDAO {
    // JDBC variables
    DataSource ds = null;
    
    public UserDAO() {
        try {
            Context ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/jdbc/leagueDataSource");
        } catch (Exception e) {
            System.err.println(e);
        }
    }
    
    public User search(String login_name, String login_password) {
        try {
            Connection conn = ds.getConnection();
            String sql = "SELECT * FROM \"User\" WHERE \"login_name\"=? AND \"login_password\"=?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, login_name);
            pstmt.setString(2, login_password);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("UID");
                String name = rs.getString("name");
                String role = rs.getString("role");
                User user = new User(id, login_name, login_password, name, role);
                return user;
            }
        } catch (Exception e) {
            System.err.println(e);
        }
        return null;
    }
}
